package org.example.project_12.controller;

import jakarta.servlet.http.HttpSession;
import org.example.project_12.dto.DocumentDto;
import org.example.project_12.dto.SpaceDto;
import org.example.project_12.entity.User;
import org.example.project_12.service.DocumentService;
import org.example.project_12.service.SpaceService;
import org.example.project_12.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/stats")
public class StatsController {
    @Autowired
    private DocumentService documentService;
    @Autowired
    private SpaceService spaceService;
    @Autowired
    private CommentService commentService;

    @GetMapping("")
    public String stats(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        // 用户统计
        Map<String, Object> userStats = new HashMap<>();
        List<DocumentDto> docs = documentService.getDocumentsByAuthor(user.getId(), user.getId());
        userStats.put("documentCount", docs != null ? docs.size() : 0);
        List<DocumentDto> favorites = documentService.getFavoriteDocuments(user.getId());
        userStats.put("favoriteCount", favorites != null ? favorites.size() : 0);
        int commentCount = commentService.getCommentsByUser(user.getId()).size();
        userStats.put("commentCount", commentCount);
        model.addAttribute("userStats", userStats);
        // 空间统计
        List<SpaceDto> spaces = spaceService.getSpacesByMemberId(user.getId());
        for (SpaceDto space : spaces) {
            // 统计成员数和文档数（假设SpaceDto已包含这些字段）
            // 如果没有，需要在SpaceServiceImpl中补充
        }
        model.addAttribute("spaceStatsList", spaces);
        return "stats";
    }
} 